package org.webdb.webapp.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class QueryString {

    public static Map<String, String> toMap(InputStream inputStream,
            String charset) throws IOException {
        return toMap(new InputStreamReader(inputStream), charset);
    }

    public static Map<String, String> toMap(Reader reader, String charset)
            throws IOException {
        HashMap<String, String> map = new HashMap<String, String>();
        StringBuilder buffer = new StringBuilder();
        String key = null;

        int i;
        while ((i = reader.read()) != -1) {
            switch (i) {
            case '=':
                key = URLDecoder.decode(buffer.toString(), charset);
                buffer.delete(0, buffer.length());
                break;
            case '&':
                map.put(key, URLDecoder.decode(buffer.toString(), charset));
                buffer.delete(0, buffer.length());
                break;
            default:
                buffer.append((char) i);
            }
        }
        if (key != null && buffer.length() > 0)
            map.put(key, URLDecoder.decode(buffer.toString(), charset));

        return map;
    }

}
